package com.yeqing.iodemo;

import java.io.*;

public class 对象流 {

    public static void 写入对象到文件中() throws Exception {
        User user = new User();
        user.setName("马超666");
        user.setAge(88);
        System.out.println(user);
        try (
                FileOutputStream fos = new FileOutputStream("/Users/cyq/Develop/三国/马超.txt");
                ObjectOutputStream oos = new ObjectOutputStream(fos)
        ) {
            oos.writeObject(user);
        }
    }

    public static void 读取对象() throws Exception {
        try (
                FileInputStream fis = new FileInputStream("/Users/cyq/Develop/三国/马超.txt");
                ObjectInputStream ois = new ObjectInputStream(fis)
        ) {
            // com.yeqing.iodemo.User@6f496d9f
            User user = (User) ois.readObject();
            System.out.println(user);
            System.out.println(user.getName() + user.getAge());
        }
    }

    public static <T> byte[] 对象转字节数组(T t) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(t);
        return baos.toByteArray();
    }

    public static <T> T 字节数组转对象(byte[] data) throws Exception {
        try (
                ByteArrayInputStream bais = new ByteArrayInputStream(data);
                ObjectInputStream ois = new ObjectInputStream(bais);
        ) {
            return (T) ois.readObject();
        }
    }

    public static void main(String[] args) throws Exception {
//        写入对象到文件中();
//        读取对象();

        User user = new User();
        user.setName("关羽");
        user.setAge(18);
        System.out.println(user);
        byte[] data = 对象转字节数组(user);
        User user2 = (User) 字节数组转对象(data);
        System.out.println(user2);

    }
}

class User implements Serializable {
    private static final long serialVersionUID = 2075103737409045180L;
    private String name;
    private Integer age;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
}


